Ccay.Module.define("Ccay.example.ui.igird.customRenderer", function(page, $S) {
	page.ready = function() {
		$S("#customRendererDemo").ccayTab();
				
		var gridOption = {
			height: 400,
			editMode: true,
			wrapHead: false,
			colsort: false,
			wrap: true,
		    columns: [
		    	{columnType: 'select', multi: true},
		 		{field: 'name', valueField: "card", width:150, header: "ccay.common.label.userAccount", type: "ldap", rule: {required: true}},
		 		{field: 'sex', width:75, header: "ccay.security.role.valid", type: 'bool', format: {isIcon: true}},
		 		{field: 'phone', width:300, header: "ccay.cms.label.attachment", editable: false, sortable: false, renderer: Ccay.example.ui.igird.customRenderer.uploadRender},
		 		{field: 'lastUpdateDate', width:130, header: "ccay.common.label.lastUpdatedDate", type: 'datetime', editable: false, content: "${#getLastTime(lastUpdateDate)}"}
		    ],
			ajax:{
			   	url: 'services/ccay/demo/student/list/page/${pageSize}/${curPage}/${orderBy}'
			},
		    operation: {
		    	del: {
		    		btn: '#btnUploadDel',
		    		undoBtn: '#btnUploadUndoDel'
		    	},
		    	insert: {
		    		btn: '#btnUploadAdd',
		    		copy: true,
		    		clear: ['id', 'name', 'lastUpdateDate'],
		    		defaultRow: {sex: 1, blog: 'http://'}
		    	},
		    	save: {
		    		btn: '#btnUploadSave',
		    		ajax: {
		    			url: "services/ccay/demo/student/batch"
		    		}
		    	}
		    }
		};

		$S("#grdUpload").igrid(gridOption);

		var gridOption2 = {
				height: 400,
				editMode: true,
				wrapHead: false,
				colsort: false,
				wrap: true,
			    columns: [
			    	{columnType: 'select', multi: true},
			 		{field: 'name', valueField: "card", width:150, header: "ccay.common.label.userAccount", type: "ldap", rule: {required: true}},
			 		{field: 'sex', width:75, header: "ccay.security.role.valid", type: 'bool', format: {isIcon: true}},
			 		{field: 'phone', width:300, header: "ccay.cms.label.attachment", editable: false, sortable: false, content:'${#Ccay.example.ui.igird.customRenderer.P2.uploadRender(data,_rowNo)}'},
			 		{field: 'lastUpdateDate', width:130, header: "ccay.common.label.lastUpdatedDate", type: 'datetime', editable: false, content: "${#getLastTime(lastUpdateDate)}"}
			    ],
				ajax:{
				   	url: 'services/ccay/demo/student/list/page/${pageSize}/${curPage}/${orderBy}'
				},
			    operation: {
			    	del: {
			    		btn: '#btnUploadDel2',
			    		undoBtn: '#btnUploadUndoDel'
			    	},
			    	insert: {
			    		btn: '#btnUploadAdd2',
			    		copy: true,
			    		clear: ['id', 'name', 'lastUpdateDate'],
			    		defaultRow: {sex: 1, blog: 'http://'}
			    	},
			    	save: {
			    		btn: '#btnUploadSave2',
			    		ajax: {
			    			url: "services/ccay/demo/student/batch"
			    		}
			    	}
			    }
			};

		$S("li[tabid='tab2']").one("click", function () {
			$S("#grdUpload2").igrid(gridOption2);
		});
	};
	
	getLastTime = function(data){
		return Ccay.Format.toDateBefore(data && data.getUTCTime());
	};
	
	// 附件列渲染
	page.uploadRender = function (value, data, col, grid, colNo, rowNo) {
		return value ? page.showAttachment(value, rowNo) : '<span class="ccay-button" onclick={1}><a class="ccay-icon upload"></a><label>{0}</label></span>'.format([$i18n("ccay.common.label.attachmentUpload"), "Ccay.example.ui.igird.customRenderer.uploadAttachment('{0}')".format(rowNo)]);
	};
	
	// 显示附件
	page.showAttachment = function (batchId, rowNo) {
		var files = [];
		Ccay.Core.ajax({
			async: false,
			url: "services/ccay/demo/attachment/biz/single/withurl",
			data: {attachmentBatchId: batchId},
			success: function (result) {
				var attachments = result && result.attachments;
				if (attachments && attachments.length) {
					$.each(attachments, function (aIdx, attachment) {
						attachment.rowIdx = rowNo;
						files.push("<div><a style='text-decoration: underline;' href='${#downloadUrl}'>${#fileName}</a><a class='ccay-icon del' onclick='Ccay.example.ui.igird.customRenderer.deleteAttachment(\"${#deleteUrl}\", this, \"${#rowIdx}\")'></a></div>".formatField(attachment));
					});
				}
			}
		});
		return files.join("");
	};
	
	// 上传附件
	page.uploadAttachment = function (rowIdx) {
		var param = {
			uploadType: "Attachment",
			completeCallback: page.uploadComplete,
			userObject: {rowIdx: rowIdx},
			needBatchId: true,
			closeDialog: true,
			query: "attType=AttachmentDemo"
		};
		Ccay.Component.openUploadDialog("ccay.common.label.attachmentUpload", param);
	};
	
	// 上传附件完成
	page.uploadComplete = function (attachments, batchId, userObject) {
		var grdUploadMag = $S("#grdUpload").manager(),
			uploadCol = grdUploadMag.getCellByField(userObject.rowIdx, "phone"),
			rowData = grdUploadMag.getRowData(uploadCol);
		uploadCol.html(page.showAttachment(batchId, userObject.rowIdx));
		rowData["phone"] = batchId;
		page.saveAttachment(rowData, false);
	};
	
	// 保存附件
	page.saveAttachment = function (rowData, isDelete) {
		var data = {items2Create: [], items2Delete: [], items2Update: []};
		isDelete ? data.items2Delete.push(rowData) : data.items2Update.push(rowData);
		Ccay.doPut("services/ccay/demo/student/batch", data);
	};
	
	// 删除附件
	page.deleteAttachment = function (url, aDom, rowNo) {
		Ccay.doDelete(url, null, function() {
			var fileDom = $(aDom).parent(), colDom = fileDom.parent();
			fileDom.remove();
			if (!colDom.html()) {
				colDom.html('<span class="ccay-button" onclick={1}><a class="ccay-icon upload"></a><label>{0}</label></span>'.format([$i18n("ccay.common.label.attachmentUpload"), "Ccay.example.ui.igird.customRenderer.uploadAttachment('{0}')".format(rowNo)]));
				var rowData = $S("#grdUpload").manager().getRowData(colDom);
				rowData["phone"] = null;
				page.saveAttachment(rowData, true);
			}
		});
	};
	
	page.P2 = {
		uploadRender : function(data,rowNo){
			rowNo = data._newIndex || rowNo;
			var value = data.phone;
			return value ? this.showAttachment(value, rowNo) : '<span class="ccay-button" onclick={1}><a class="ccay-icon upload"></a><label>{0}</label></span>'.format([$i18n("ccay.common.label.attachmentUpload"), "Ccay.example.ui.igird.customRenderer.P2.uploadAttachment('{0}')".format(rowNo)]);
		},
		showAttachment : function (batchId, rowNo) {
			var files = [];
			Ccay.Core.ajax({
				async: false,
				url: "services/ccay/demo/attachment/biz/single/withurl",
				data: {attachmentBatchId: batchId},
				success: function (result) {
					var attachments = result && result.attachments;
					if (attachments && attachments.length) {
						$.each(attachments, function (aIdx, attachment) {
							attachment.rowIdx = rowNo;
							files.push("<div><a style='text-decoration: underline;' href='${#downloadUrl}'>${#fileName}</a><a class='ccay-icon del' onclick='Ccay.example.ui.igird.customRenderer.P2.deleteAttachment(\"${#deleteUrl}\", this, \"${#rowIdx}\")'></a></div>".formatField(attachment));
						});
					}
				}
			});
			return files.join("");
		},
		uploadAttachment : function(rowIdx){
			var param = {
				uploadType: "Attachment",
				completeCallback: Ccay.example.ui.igird.customRenderer.P2.uploadComplete,
				userObject: {rowIdx: rowIdx},
				needBatchId: true,
				closeDialog: true,
				query: "attType=AttachmentDemo"
			};
			Ccay.Component.openUploadDialog("ccay.common.label.attachmentUpload", param);
		},
		uploadComplete : function (attachments, batchId, userObject) {
			var grdUploadMag = $S("#grdUpload2").manager(),
				uploadCol = grdUploadMag.getCellByField(userObject.rowIdx, "phone"),
				rowData = grdUploadMag.getRowData(uploadCol);
			if(!rowData._inserted && !rowData._deleted){
				uploadCol.addClass("cell-update");
				rowData._updated = true;
			}
			uploadCol.html(page.P2.showAttachment(batchId, userObject.rowIdx));
			rowData["phone"] = batchId;
		},
		deleteAttachment : function (url, aDom, rowNo) {
			Ccay.doDelete(url, null, function() {
				var fileDom = $(aDom).parent(), colDom = fileDom.parent();
				fileDom.remove();
				if (!colDom.html()) {
					colDom.html('<span class="ccay-button" onclick={1}><a class="ccay-icon upload"></a><label>{0}</label></span>'.format([$i18n("ccay.common.label.attachmentUpload"), "Ccay.example.ui.igird.customRenderer.P2.uploadAttachment('{0}')".format(rowNo)]));
					var rowData = $S("#grdUpload2").manager().getRowData(colDom);
					if(!rowData._inserted && !rowData._deleted){
						colDom.addClass("cell-update");
						rowData._updated = true;
					}
					rowData["phone"] = null;
				}
			});
		}
	};
});